<template>
  <div>
    <el-card shadow="always" style="margin: 20px">
      <el-form :inline="false" size="normal">
        <el-form-item label="" size="normal">
          <el-input
            type="text"
            style="width: 20%; margin-right: 20px"
            placeholder="用户名"
            size="small"
            v-model="searchName"
          >
          </el-input>
          <el-button
            type="primary"
            size="small"
            @click="getUserLists"
            icon="el-icon-search"
            >查询</el-button
          >
          <el-button size="small" @click="searchName = ''">清空</el-button>
        </el-form-item>
      </el-form>

      <el-button
        type="primary"
        style="margin-right: 20px"
        size="small"
        @click="showDialogBox()"
        >添加</el-button
      >

      <!-- 这里版本原因需要再事件前面添加一个on -->
      <el-popconfirm
        confirm-button-text="确定"
        cancel-button-text="取消"
        title="确定删除选中的用户吗？"
        @onConfirm="delAll"
      >
        <el-button
          type="danger"
          :disabled="selectList.length < 1"
          size="small"
          slot="reference"
          >批量删除</el-button
        >
      </el-popconfirm>
      <!-- 表格 -->
      <el-table
        border
        stripe
        style="margin-top: 20px"
        :data="userList"
        @selection-change="selectCurrent"
      >
        <el-table-column type="selection" checked="selectCurrent" />

        <el-table-column type="index" width="55" label="序号" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="用户昵称" prop="nickName" />
        <el-table-column label="角色列表" prop="roleName" />
        <el-table-column label="创建时间" prop="gmtCreate" />
        <el-table-column label="更新时间" prop="gmtModified" />
        <el-table-column label="操作">
          <template v-slot="{ row, index }">
            <el-button
              type="info"
              size="mini"
              @click="showEditBox(row)"
              icon="el-icon-user-solid"
            ></el-button>

            <el-button
              type="primary"
              size="mini"
              @click="showDialogBox(row)"
              icon="el-icon-edit"
            ></el-button>

            <!-- 删除按钮 -->
            <el-popconfirm
              style="margin-left: 10px"
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定删除当前的用户吗？"
              @onConfirm="DelUserInfo(row)"
            >
              <el-button
                type="danger"
                size="mini"
                @click=""
                icon="el-icon-delete"
                slot="reference"
              ></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="page"
        :page-sizes="[3, 5, 7]"
        :page-size="limit"
        layout=" prev, pager, next,jumper,->, sizes,total"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加或修改用户的弹窗 -->
    <el-dialog
      :title="formData.id ? '修改用户' : '添加用户'"
      :model="true"
      top="0"
      width="50%"
      :visible="showDialog"
      :show-close="false"
    >
      <el-form
        label-width="120px"
        :model="formData"
        size="normal"
        ref="rulesForm"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input size="small" v-model="formData.username"></el-input>
        </el-form-item>

        <el-form-item label="用户昵称">
          <el-input size="small" v-model="formData.Nickname"></el-input>
        </el-form-item>

        <el-form-item label="用户密码" prop="password" v-if="!formData.id">
          <el-input
            size="small"
            show-password
            v-model="formData.password"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="addUser('rulesForm')">确定</el-button>
      </template>
    </el-dialog>

    <!-- 设置角色 -->
    <el-dialog
      title="设置角色"
      width="50%"
      :model="true"
      :visible="showEdit"
      top="0"
      :show-close="false"
    >
      <el-form ref="form" label-width="80px" size="normal">
        <el-form-item size="normal" label="用户名">
          <el-input
            :disabled="true"
            v-model="formData.username"
            size="normal"
          ></el-input>
        </el-form-item>

        <el-form-item label="角色列表" size="normal">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="checkedRoles"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="role in AllRoles"
              :label="role.roleName"
              :key="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" size="default" @click="AssignRoles"
          >保存</el-button
        >
        <el-button size="default" @click="showEdit = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  getUserList,
  reqDelAll,
  reqAddUser,
  reqUpDateUsr,
  reqDelUserInfo,
  reqUserRole,
  reqAssignRoles,
} from "@/api/getControl.js";
import { Message } from "element-ui";
export default {
  name: "User",
  data() {
    return {
      isIndeterminate: true,
      checkedRoles: [],
      AllRoles: [],
      checkAll: false,
      showEdit: false,
      page: 1,
      total: 10,
      limit: 5,
      userList: [],
      searchName: "",
      selectList: [],
      showDialog: false,
      showPassword: true,
      // 当前用户的信息
      formData: {
        username: "",
        nickName: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "用户名不能为空" },
          {
            pattern: /^[\u4e00-\u9fa5\w-]{2,20}$/,
            message: "可输入2-20位中文、字母、数字，下划线，-",
          },
        ],
        password: [
          { required: true, message: "密码不能为空" },
          {
            pattern: /^[0-9a-zA-Z_]{2,12}$/,
            message: "可输入2-12位字母数字下划线",
          },
        ],
      },
    };
  },
  mounted() {
    this.getUserLists();
  },
  methods: {
    // 获取和条件搜索用户列表
    async getUserLists() {
      let { page, limit, searchName } = this;
      try {
        const result = await getUserList(page, limit, searchName);

        this.total = result.data.total;
        this.userList = result.data.items;
        Message.success("获取用户列表成功");
      } catch (error) {
        Message.error("获取用户列表失败");
      }
    },
    // 修改每页数量
    sizeChange(limit) {
      this.limit = limit;
      this.getUserLists();
    },
    // 修改页码
    currentChange(page) {
      this.page = page;
      this.getUserLists();
    },
    selectCurrent(selection) {
      this.selectList = selection;
    },

    // 点击批量删除
    async delAll() {
      let idList = this.selectList.map((item) => {
        return item.id;
      });
      // 这个接口是坏的，代码没错，别试了
      try {
        await reqDelAll(idList);
        this.getUserLists();
        Message.success("批量删除用户成功");
      } catch (error) {
        Message.error("批量删除用户失败");
      }
    },

    // 点击添加按钮显示dialog
    showDialogBox(userInfo) {
      this.showDialog = true;
      // 因为dialog没有创建出来，所以在这之前是没有form表单这个对象的
      // 所以需要等dialog渲染出来之后才能重置表单验证的规则
      // 这里就需要用到nextTick，在页面渲染好之后才进行下一步

      this.$nextTick(() => {
        // 重置表单验证
        this.$refs.rulesForm.resetFields();
        if (userInfo) {
          // 修改
          this.showPassword = false;
          this.formData = userInfo;
        } else {
          // 添加
          this.showPassword = true;
          this.formData = {
            username: "",
            nickname: "",
            password: "",
          };
        }
      });
    },

    // form表单的验证
    rulesFormDate(formName) {
      return this.$refs[formName].validate();
    },

    // 点击确定验证添加用户form表单的信息并发送保存的请求
    async addUser(formName) {
      try {
        await this.rulesFormDate(formName);

        if (this.formData.id) {
          await reqUpDateUsr(this.formData);
          Message.success("修改成功");
        } else {
          await reqAddUser(this.formData);
          Message.success("添加成功");
        }
        this.showDialog = false;
        this.getUserLists();
      } catch (error) {
        this.formData.id
          ? Message.error("修改失败")
          : Message.error("添加失败");
      }
    },

    // 点击删除按钮删除单个用户
    async DelUserInfo(user) {
      try {
        await reqDelUserInfo(user.id);
        this.getUserLists();
        this.message("删除成功", "success");
      } catch (error) {
        this.message("删除失败", "error");
      }
    },

    // edit界面显示
    async showEditBox(obj) {
      this.showEdit = true;
      this.formData = obj;
      try {
        const result = await reqUserRole(this.formData.id);
        // console.log(result)
        this.AllRoles = result.data.allRolesList;
        this.checkedRoles = result.data.assignRoles.map((item) => {
          return item.roleName;
        });
      } catch (error) {}
    },

    // 保存用户的角色信息
    async AssignRoles() {
      let userId = this.formData.id;
      let roleId = this.checkedRoles.reduce((prev, item) => {
        // 需要双重循环，先获取到已选择到的名字

        // 再从所有角色中找到选择的角色名字，然后把这个名字的id返回
        this.AllRoles.forEach(item1 => {
          if (item1.roleName === item) {
            prev.push(item1.id)
          }
        });

        return prev;
      }, []);
     
      roleId = roleId.join(',')
      try {
        await reqAssignRoles(userId,roleId)
        Message.success('保存用户角色成功')
        this.showEdit = false;
        this.getUserLists();
      } catch (error) {
        Message.error('保存用户角色失败')

      }
    },

    // 编辑界面的全选逻辑
    handleCheckAllChange(val) {
      this.checkedRoles = val ? this.AllRoles : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.AllRoles.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.AllRoles.length;
    },
  },
};
</script>

<style scoped></style>
